using System;
using System.Text;
using System.Threading.Tasks;
using CHEnhanceEfCore.Common;
using Microsoft.Extensions.DependencyInjection;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace CHEnhanceEfCore.Config.MQ.factory
{
    public class RabbitMqTemplate
    {
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="exchange"></param>
        /// <param name="queueName"></param>
        /// <param name="message"></param>
        /// <param name="handler">回调函数</param>
        public void sendMessage(string exchange = "", string queueName = "", string message = "", EventHandler<BasicReturnEventArgs> handler = null)
        {
            using var serviceScope = OperationalComponentUtil.serviceProvider.CreateScope();
            var rabbitMqFactory = serviceScope.ServiceProvider.GetService<RabbitMqFactory>();
            if (rabbitMqFactory != null)
            {
                IModel channel = rabbitMqFactory.getChannel();
                var body = Encoding.UTF8.GetBytes(message);

                var properties = channel.CreateBasicProperties();
                //持久消息
                properties.Persistent = true;

                channel.BasicPublish(exchange, queueName, properties, body);
                channel.BasicReturn += handler;
            }
            else
            {
                Console.WriteLine("RabbitMqFactory is not register");
            }
        }

        public async Task sendMessageToQueue(string queueName, string message)
        {
            await Task.Run(() => { sendMessage("", queueName, message); });
        }
    }
}